package com.cyanite.playlv2;

import com.cyanite.playlv2.preferences.Preferences;
import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2api.PlayLv2Api;
import com.cyanite.playlv2api.util.ConstantsUtils;
import com.cyanite.playlv2.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class SignUpActivity extends Activity {

    private AsyncTask<Void, Void, Boolean> mSignUpTask;
    private ProgressDialog mProgressDialog;

    private Flag mFlagUserName = new Flag(false);
    private Flag mFlagEmail = new Flag(false);
    private Flag mFlagPassword = new Flag(false);
    private Flag mFlagPhoneNumber = new Flag(false);

    private EditText mUserName, mEmail, mPassword, mPhone;
    private Button mBtnSignUp;

    private RadioGroup mChooseSex;
    private RadioButton mFemale;
    private String mGender;
    private OnClickListener mBtnClickListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.sign_up_activity);

        mUserName = (EditText) findViewById(R.id.userName);
        mEmail = (EditText) findViewById(R.id.email);
        mPassword = (EditText) findViewById(R.id.password);
        mPhone = (EditText) findViewById(R.id.phoneNumber);

        mUserName.addTextChangedListener(mTwUserName);
        mEmail.addTextChangedListener(mTwEmail);
        mPassword.addTextChangedListener(mTwPassword);
        mPhone.addTextChangedListener(mTwPhoneNumber);

        mBtnSignUp = (Button) findViewById(R.id.registButton);
        mBtnClickListener = new OnClickListener() {
            public void onClick(View v) {
                mSignUpTask = new SignUpTask(SignUpActivity.this);
                mSignUpTask.execute();
            }
        };
        mBtnSignUp.setOnClickListener(mBtnClickListener);
        mBtnSignUp.setEnabled(false);

        mChooseSex = (RadioGroup) findViewById(R.id.rgChooseSex);
        mFemale = (RadioButton) findViewById(R.id.rbtnFemale);
        mFemale.setChecked(true);
        mGender = getString(R.string.gender_female);
        mChooseSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
               if(checkedId == mFemale.getId()){
                   mGender = SignUpActivity.this.getString(R.string.gender_female);
                }
               else{
                   mGender = SignUpActivity.this.getString(R.string.gender_male);
               }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
            finish();
            return true;
        }
        else
            return super.onKeyDown(keyCode, event);
    }

    private void associateButton(CharSequence aCharSequence, Flag aFlag) {
        if (aFlag.getFlag()) {
            if ( TextUtils.isEmpty(aCharSequence) ) {
                aFlag.toggleFlag();
            }
        }   else {
            if ( !TextUtils.isEmpty(aCharSequence) ) {
                aFlag.toggleFlag();
            }
        }

        if ( mFlagUserName.getFlag() && mFlagEmail.getFlag() && mFlagPassword.getFlag() ) {
            String email = mEmail.getText().toString();
            int pos1 = email.indexOf("@");
            int pos2 = email.indexOf(".", pos1);
            if (pos1 < (pos2-1) && pos1 > 0 && pos2 > 0 && pos2 < email.length()-1) {
                mBtnSignUp.setEnabled(true);
            }   else {
                mBtnSignUp.setEnabled(false);
            }
        }   else {
            mBtnSignUp.setEnabled(false);
        }
    }


    private TextWatcher mTwUserName = new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            associateButton(s, mFlagUserName);
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void afterTextChanged(Editable s) {
        }
    };

    private TextWatcher mTwEmail = new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            associateButton(s, mFlagEmail);
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void afterTextChanged(Editable s) {
        }
    };

    private TextWatcher mTwPassword = new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            associateButton(s, mFlagPassword);
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void afterTextChanged(Editable s) {
        }
    };

    private TextWatcher mTwPhoneNumber = new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            associateButton(s, mFlagPhoneNumber);
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void afterTextChanged(Editable s) {
        }
    };

    private class SignUpTask extends AsyncTask<Void, Void, Boolean> {

        private Exception mReason;
        private PlayLv2 mPlayLv2;

        public SignUpTask(SignUpActivity activity) {
            mPlayLv2 = ((PlayLv2) activity.getApplication());
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(SignUpActivity.this);
            Editor editor = prefs.edit();
            boolean signup = false;
            PlayLv2Api playlv2api = mPlayLv2.getPlayLv2Api();
            String account = mUserName.getText().toString();
            String email = mEmail.getText().toString();
            String phone = mPhone.getText().toString();
            String password = mPassword.getText().toString();
            String gender = mGender.equals("Ů")?"2":"1";
            Location loc = mPlayLv2.getLastKnownLocation();
            if (loc == null) {
                try { Thread.sleep(ConstantsUtils.SLEEP_TIME_IF_NO_LOCATION); } catch (InterruptedException ex) {}
                loc = mPlayLv2.getLastKnownLocation();
            }
            try {
                    String country = null;
                    String province = null;
                    String city = null;
                    String street = null;
                    if (loc != null)    {
                        List<Address> addresses = getAdressFromLocation(loc);
                        if( addresses != null && addresses.size() > 0 )  {
                            Address address=addresses.get(0);
                            if ( address != null ) {
                                country = address.getCountryName();
                                city = address.getLocality();
                            }
                        }
                    }
                    signup = Preferences.signupUser(playlv2api, account, password, phone,
                                    email, gender, country, province, city, street, editor);
            } catch (Exception ex) {
                mReason = ex;
                return false;
            }
            return signup;
        }

        @Override
        protected void onPostExecute(Boolean signup) {
            if (signup) {
                sendBroadcast(new Intent(PlayLv2.INTENT_ACTION_LOGGED_IN));
                Toast.makeText(SignUpActivity.this, getString(R.string.login_welcome_toast),
                        Toast.LENGTH_LONG).show();

                Intent intent = new Intent(SignUpActivity.this, BlogBindActivity.class);
                intent.putExtra(BlogBindActivity.EXTRA_MAIN, 1);
                startActivity(intent);
                // Be done with the activity.
                finish();

            } else {
                sendBroadcast(new Intent(PlayLv2.INTENT_ACTION_LOGGED_OUT));
                NotificationsUtil.ToastReasonForFailure(SignUpActivity.this, mReason);
            }
            dismissProgressDialog();
        }

        @Override
        protected void onCancelled() {
            dismissProgressDialog();
        }
    }

    private ProgressDialog showProgressDialog() {
        if (mProgressDialog == null) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.sign_up_dialog_message));
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            mProgressDialog = dialog;
        }
        mProgressDialog.show();
        return mProgressDialog;
    }

    private void dismissProgressDialog() {
        try {
            mProgressDialog.dismiss();
        } catch (IllegalArgumentException e) {
            // We don't mind. android cleared it for us.
        }
    }

    private class Flag {
        private Boolean mDataFlag;
        Flag(Boolean aFlag) {
            mDataFlag = aFlag;
        }
        public void toggleFlag() {
            mDataFlag = !mDataFlag;
        }
        public Boolean getFlag() {
            return mDataFlag;
        }
    }

    private List<Address> getAdressFromLocation(Location location)   {
        if (location != null)  {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            Geocoder gc = new Geocoder(this,Locale.getDefault());
            try {
                List<Address> addresses = gc.getFromLocation( latitude, longitude, 1 );
                return addresses;
            }catch(IOException e){}
        }
        return null;
    }
}
